package com.parking.common.core.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.parking.common.core.exception.ParkingException;
import lombok.Data;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.stereotype.Component;

import java.io.IOException;
public class CardIdUtil {

    /**
     * 身份证校验
     *  @Pattern(message = "cardId不符合格式", regexp = "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}([0-9]|X)$")
     *
     *
     * 导包信息
     * <dependency>
     *     <groupId>com.squareup.okhttp3</groupId>
     *     <artifactId>okhttp</artifactId>
     *     <version>3.13.1</version>
     * </dependency>
     * */
    @Data
    public static class CardUtilDto2 {
        String name;
        String idcard;
        Integer res;
        String description;
        String sex;
        String birthday;
        String address;
    }

    @Data
    public static class CardUtilDto {
        String code;
        String message;
        CardUtilDto2 result;
    }

    public static boolean checkIdCard(String cardId, String realName) throws IOException {
        String url = "https://eid.shumaidata.com/eid/check";
        String appCode = "348cca4fa6024539bd35c778a048e332";

        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();

        formbuilder.add("name",realName);
        formbuilder.add("idcard",cardId);

        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        String result = client.newCall(request).execute().body().string();

        ObjectMapper objectMapper = new ObjectMapper();
        CardUtilDto dto = objectMapper.readValue(result,CardUtilDto.class);

        if (!"0".equals(dto.getCode())) { // 手动将字符串值转换为整数进行判断
            throw new ParkingException("身份证或姓名无效", 8000);
        }

        return dto.getResult().getDescription().equals("一致");
    }
}
